package com.sky.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.user.UserDishFlavorMapper;
import com.sky.mapper.user.UserDishMapper;
import com.sky.service.user.DishService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("userDishService")
@RequiredArgsConstructor
public class DishServiceImpl extends ServiceImpl<UserDishMapper,Dish> implements DishService {
    public final UserDishMapper dishMapper;
    public final UserDishFlavorMapper dishFlavorMapper;

    @Override
    @Cacheable(cacheNames = "dish", key = "#categoryId", unless = "#result == null || #result.isEmpty()")
    public List<DishVO> findAllByCategoryId(Integer categoryId) {

            // 1. 一次性查询所有菜品
            List<Dish> dishList = dishMapper.selectList(new QueryWrapper<Dish>()
                    .eq(categoryId != null,"category_id", categoryId)
                    .eq("status", 1));

            // 2. 收集所有菜品ID
            List<Integer> dishIds = dishList.stream()
                    .map(Dish::getId)
                    .toList();

            // 3. 批量查询所有口味信息
            List<DishFlavor> allFlavors = new ArrayList<>();
            if (!dishIds.isEmpty()) {
                allFlavors = dishFlavorMapper.selectList(new QueryWrapper<DishFlavor>().in("dish_id", dishIds));
            }

            // 4. 按dish_id分组口味信息
            Map<Integer, List<DishFlavor>> flavorMap = allFlavors.stream()
                    .collect(Collectors.groupingBy(DishFlavor::getDishId));

            // 5. 组装结果
            return dishList.stream().map(dish -> {
                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(dish, dishVO);
                dishVO.setFlavors(flavorMap.getOrDefault(dish.getId(), new ArrayList<>()));
                return dishVO;
            }).toList();
    }
}
